﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SyncList.Business.Persistence;
using SyncList.UserInterface;
using System.IO;
using SyncList.Business.ValueObject;
using SyncList.Business;
using SyncList.UserInterface.ValueObject;
using System.Diagnostics;
using SyncList.UserInterface.Helpers;
using Microsoft.Win32;

namespace SyncList.Win
{
	/// <summary>
	/// Interaction logic for WindowCompare.xaml
	/// </summary>
	public partial class WindowCompare : Window
    {

        #region Attributs


        /// <summary>
        /// Liste des listes chargées
        /// </summary>
        private List<Data> _listOfFileToCompare = new List<Data>();

        /// <summary>
        /// Organisation en dossiers
        /// </summary>
        private DirectoryContent _root = null;

        /// <summary>
        /// Liste de mes fichiers
        /// </summary>
        private Data[] _myDataList;



        #endregion Variables
        
        /// <summary>
        /// Constructeur
        /// </summary>
		public WindowCompare()
		{
			this.InitializeComponent();

            StartHelper.Start(MenuBar);
            MenuBar.ExitAction = () => this.Close();

            //this.BtnExplorer.Click += new RoutedEventHandler(BtnExplorer_Click);
            this.AllowDrop = true;
            this.Drop += new DragEventHandler(WindowCompare_Drop);


            ImagePanier.Fill = IconHelper.GetImageBrush("panier.png");

            this.ucExplorer.ItemsSelected += new EventHandler<DragDropEventArgs>(ucExplorer_ItemsSelected);
            this.ucBasket.ItemsDropped += new EventHandler<DragDropEventArgs>(ucBasket_ItemsDropped);
            this.ucBasket.ItemsSelected += new EventHandler<DragDropEventArgs>(ucBasket_ItemsSelected);
            this.BtnAutoAdd.Click += new RoutedEventHandler(BtnAutoAdd_Click);
            this.BtnGetIt.Click += new RoutedEventHandler(BtnGetIt_Click);
		}





        /// <summary>
        /// Ajouter automatiquement tous les fichiers marqués comme "j'ai pas"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BtnAutoAdd_Click(object sender, RoutedEventArgs e)
        {
            string currentUser = MemoryStorage.Instance.Settings.UserName;
            DirectoryContent[] users = ucExplorer.Root.Directories.Values.Where(d=> !d.Name.Equals(currentUser)).ToArray();
            
            foreach(DirectoryContent user in users)
            {
                IEnumerable<FileItem> files = user.AllFiles.Where(af => af.State == ExplorerItemState.IDontHaveFile);
                foreach (FileItem file in files)
                    AddFileToBasket(file);
            }
        }


     

        
        /// <summary>
        /// Accepter le Drop de lists
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void WindowCompare_Drop(object sender, DragEventArgs e)
        {
                 
            //Récupère le path du fichier que l'on vient de glisser-déposer sur l'interface de comparaison !
            string[] _filePath = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (_filePath == null)
                return;

            foreach (string filePath in _filePath)
            {
                if (!File.Exists(filePath))
                    continue;

                // - On récupère un FileInfo sur le fichier qui vient d'être déposé.
                FileInfo currentFileDropped = new FileInfo(filePath);

                // - On vérifie que le fichier est bien au format XML
                if (!currentFileDropped.Extension.ToLower().Equals(".syl"))
                    continue;


                //Apres vérification de la structure XML du fichier droppé, soit on l'accepte...soit....bah pas !!
                //si on l'accepte, on créé l'élément Data correspondant.

                // - Rechercher si j'ai déjà importé le fichier en question pour l'ignorer
                Data search = _listOfFileToCompare.FirstOrDefault(f => f.XmlFileName.Equals(currentFileDropped.FullName));
                if (search == null)
                {
                    Data currentData = ServiceAccessor.ImportService.ImportList(currentFileDropped.FullName);
                    _listOfFileToCompare.Add(currentData);
                }

            }

            // - Nouveau dév EL
            string currentUserName = MemoryStorage.Instance.Settings.UserName;
            //Data[] otherLists = _listOfFileToCompare.Where(list => !currentUserName.Equals(list.UserName)).ToArray();         

            _myDataList = _listOfFileToCompare.Where(list => currentUserName.Equals(list.UserName)).ToArray();         

            _root = ServiceAccessor.FusionService.OrganizeInDirectories(_listOfFileToCompare, currentUserName);

            ServiceAccessor.FusionService.CheckFiles(_root, _listOfFileToCompare, currentUserName);


            if (_root == null)
                TextBlockMessage.Visibility = System.Windows.Visibility.Visible;
            else
                TextBlockMessage.Visibility = System.Windows.Visibility.Collapsed;


            if(_root != null)
                ucExplorer.Initialize(_root);

            //List<string> extensions = new List<string>();
            //foreach (Data data in _listOfFileToCompare)
            //{
            //    foreach (FileItem fileDef in data.Files)
            //    {
            //        string extension = fileDef.Extension.ToLower();
            //        if (!extensions.Contains(extension))
            //            extensions.Add(extension);
            //    }
            //}
            //Debug.WriteLine("------------------ EXTENSIONS");
            //foreach (string extension in extensions.OrderBy(ext => ext))
            //    Debug.WriteLine(extension);
            
        }


      
        /// <summary>
        /// Items ajoutés à droite
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ucBasket_ItemsDropped(object sender, DragDropEventArgs e)
        {

            // - Tout ajouter dans le panier

            foreach (ItemBase item in e.Items)
            {
                DirectoryContent directory = item as DirectoryContent;
                if (directory != null)
                {
                    foreach (FileItem dirFile in directory.AllFiles)
                        AddFileToBasket(dirFile);                        
                }

                FileItem file = item as FileItem;
                if (file != null)
                    AddFileToBasket(file);
                    //ucBasket.Root.PlaceFileInTree(file, null);
            }
            ucBasket.CurrentDirectory = ucBasket.Root;

        }




        /// <summary>
        /// Essayer de supprimer ces items
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ucBasket_ItemsSelected(object sender, DragDropEventArgs e)
        {
            foreach(ItemBase item in e.Items)
            {
                DirectoryContent directory = item as DirectoryContent;
                if (directory != null)
                    RemoveFiles(directory.AllFiles);

                FileItem file = item as FileItem;
                if (file != null)
                    RemoveFile(file);
            }
        }


        /// <summary>
        /// Supprimer des fichiers
        /// </summary>
        /// <param name="source"></param>
        private void RemoveFiles(IEnumerable<FileItem> source)
        {
            foreach (FileItem item in source)
                RemoveFile(item);
        }

        /// <summary>
        /// Supprimer des fichiers
        /// </summary>
        /// <param name="source"></param>
        private void RemoveFile(FileItem item)
        {
            ucBasket.Root.RemoveItemFromTree(item);
        }


        /// <summary>
        /// Sélection dans l'explorateur d'un fichier
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ucExplorer_ItemsSelected(object sender, DragDropEventArgs e)
        {
            foreach (ItemBase item in e.Items)
            {
                FileItem file = item as FileItem;
                if (file != null)
                    AddFileToBasket(file);
            }
        }

        /// <summary>
        /// Ajouter un fichier au panier
        /// </summary>
        /// <param name="file"></param>
        public void AddFileToBasket(FileItem file)
        {
            DirectoryContent root = ucBasket.Root;
            DirectoryContent userDirectory = root.GetDirectory(file.UserName);
            userDirectory.DirectoryType = DirectoryTypeEnum.User;
            userDirectory.PlaceFileInTree(file, file.LocalFolder);

            //ucBasket.Root.AddFile(file);

            //ucBasket.Root.PlaceFileInTree(file, null);
        }


        /// <summary>
        /// Exporter une liste de fichiers désirés
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BtnGetIt_Click(object sender, RoutedEventArgs e)
        {
            //FileItem[] allFiles = ucBasket.Root.AllFiles.ToArray();

            string extension = ".syw";

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.OverwritePrompt = true;
            dialog.FilterIndex = 0;
            dialog.Filter = "Fichiers Wish (*" + extension + ")|*"+ extension +"|Tous les fichiers (*.*)|*.*";
            if (dialog.ShowDialog() == true)
            {
                string fileName = dialog.FileName;
                if (!String.IsNullOrWhiteSpace(fileName))
                {
                    if (!fileName.EndsWith(extension))
                        MessageBox.Show("Le nom du fichier doit obligatoirement porter l'extension '"+ extension +"'");
                    else
                        ServiceAccessor.ExportService.ExportWishes(ucBasket.Root, fileName);
                }
            }
            
        }



    }
}
